<template>
  <uni-popup ref="popup" type="center" :mask-click="false">
    <view class="payment-modal">
      <!-- 支付标题 -->
      <view class="payment-header">
        <view class="payment-title">发布任务支付</view>
        <view class="close-btn" @tap="handleClose">
          <uni-icons type="close" size="20" color="#999" />
        </view>
      </view>

      <!-- 任务信息 -->
      <view class="task-info">
        <view class="task-title">{{ taskInfo.title }}</view>
        <view class="task-desc">{{ taskInfo.description }}</view>
      </view>

      <!-- 费用明细 -->
      <view class="fee-breakdown">
        <view class="breakdown-title">费用明细</view>
        <view class="breakdown-item">
          <text>悬赏金额</text>
          <text class="fee">¥{{ reward }}</text>
        </view>
        <view class="breakdown-item">
          <text>基础发布费</text>
          <text class="fee">¥{{ baseFee }}</text>
        </view>
        <view class="breakdown-item" v-if="urgentFee > 0">
          <text>加急费用</text>
          <text class="fee">+¥{{ urgentFee }}</text>
        </view>
        <view class="breakdown-item total">
          <text>总计</text>
          <text class="total-fee">¥{{ totalFee }}</text>
        </view>
      </view>

      <!-- 钱包余额显示 -->
      <view class="wallet-balance">
        <view class="balance-info">
          <text class="balance-label">当前余额</text>
          <text class="balance-amount">¥{{ userBalance }}</text>
        </view>
        <view class="balance-status" :class="{ insufficient: userBalance < totalFee }">
          <text v-if="userBalance >= totalFee">余额充足</text>
          <text v-else>余额不足，需要充值</text>
        </view>
      </view>

      <!-- 支付方式选择 -->
      <view class="payment-methods">
        <view class="methods-title">支付方式</view>
        <view class="method-list">
          <view 
            class="method-item" 
            v-for="method in paymentMethods" 
            :key="method.id"
            :class="{ active: selectedMethod === method.id, disabled: userBalance < totalFee && method.id === 'wallet' }"
            @tap="selectPaymentMethod(method.id)"
          >
            <view class="method-icon">
              <uni-icons :type="method.icon" size="24" :color="method.color" />
            </view>
            <view class="method-info">
              <text class="method-name">{{ method.name }}</text>
              <text class="method-desc">{{ method.desc }}</text>
            </view>
            <view class="method-radio">
              <uni-icons 
                :type="selectedMethod === method.id ? 'checkbox-filled' : 'circle'" 
                size="20" 
                :color="selectedMethod === method.id ? '#00BFFF' : '#ddd'" 
              />
            </view>
          </view>
        </view>
      </view>

      <!-- 余额不足时的充值提示 -->
      <view class="recharge-tip" v-if="userBalance < totalFee">
        <view class="tip-content">
          <uni-icons type="info" size="16" color="#FF6B6B" />
          <text class="tip-text">余额不足，请先充值</text>
        </view>
        <button class="recharge-btn" @tap="goToRecharge">立即充值</button>
      </view>

      <!-- 支付按钮 -->
      <view class="payment-actions">
        <button class="cancel-btn" @tap="handleClose">取消</button>
        <button class="pay-btn" @tap="handlePayment" :disabled="!selectedMethod || userBalance < totalFee">
          {{ userBalance < totalFee ? '余额不足' : '立即支付' }} ¥{{ totalFee }}
        </button>
      </view>
    </view>
  </uni-popup>
</template>

<script>
export default {
  name: 'PaymentModal',
  props: {
    taskInfo: {
      type: Object,
      default: () => ({})
    },
    reward: {
      type: Number,
      default: 0
    },
    baseFee: {
      type: Number,
      default: 5
    },
    urgentFee: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      selectedMethod: 'wallet',
      userBalance: 0,
      paymentMethods: [
        {
          id: 'wallet',
          name: '钱包余额',
          desc: '使用账户余额支付（推荐）',
          icon: 'wallet',
          color: '#00BFFF'
        }
      ]
    }
  },
  computed: {
    totalFee() {
      return Number(this.reward) + this.baseFee + this.urgentFee
    }
  },
  methods: {
    show() {
      this.$refs.popup.open()
      this.getUserBalance()
    },
    hide() {
      this.$refs.popup.close()
    },
    handleClose() {
      this.$emit('cancel')
      this.hide()
    },
    selectPaymentMethod(methodId) {
      this.selectedMethod = methodId
    },
    // 获取用户余额
    async getUserBalance() {
      try {
        const res = await uniCloud.callFunction({
          name: 'getUserInfo'
        })
        if (res.result.code === 200) {
          this.userBalance = res.result.data.balance || 0
        }
      } catch (error) {
        console.error('获取用户余额失败：', error)
      }
    },
    // 跳转到充值页面
    goToRecharge() {
      this.hide()
      uni.navigateTo({
        url: '/pages/user/Wallet/Wallet'
      })
    },
    async handlePayment() {
      if (!this.selectedMethod) {
        uni.showToast({
          title: '请选择支付方式',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({
          title: '支付中...'
        })

        // 打印本地token调试
        console.log('[PaymentModal] uni_id_token:', uni.getStorageSync('uni_id_token'));

        // 调用支付云函数
        const paymentResult = await uniCloud.callFunction({
          name: 'processPayment',
          data: {
            amount: this.totalFee,
            paymentMethod: this.selectedMethod,
            taskInfo: this.taskInfo,
            type: 'task_publish'
          }
        })


        uni.hideLoading()

        if (paymentResult.result.code === 200) {
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          })
          
          this.$emit('success', {
            paymentId: paymentResult.result.data.paymentId,
            amount: this.totalFee,
            method: this.selectedMethod
          })
          
          this.hide()
        } else {
          uni.showToast({
            title: paymentResult.result.msg || '支付失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '支付失败，请重试',
          icon: 'none'
        })
        console.error('支付失败：', error)
      }
    }
  }
}
</script>

<style scoped>
.payment-modal {
  width: 600rpx;
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.payment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #f0f0f0;
}

.payment-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  padding: 10rpx;
}

.task-info {
  margin-bottom: 30rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
}

.task-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8rpx;
}

.task-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.fee-breakdown {
  margin-bottom: 30rpx;
}

.breakdown-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 20rpx;
}

.breakdown-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
  font-size: 14px;
  color: #666;
}

.breakdown-item.total {
  margin-top: 20rpx;
  padding-top: 15rpx;
  border-top: 1px solid #f0f0f0;
  font-weight: 500;
  color: #333;
}

.fee {
  color: #FF9F1C;
}

.total-fee {
  color: #FF4D4F;
  font-size: 16px;
}

.payment-methods {
  margin-bottom: 30rpx;
}

.methods-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 20rpx;
}

.method-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  margin-bottom: 15rpx;
  border: 2rpx solid #f0f0f0;
  border-radius: 12rpx;
  transition: all 0.3s ease;
}

.method-item.active {
  border-color: #00BFFF;
  background: #f0f8ff;
}

.method-icon {
  margin-right: 20rpx;
}

.method-info {
  flex: 1;
}

.method-name {
  display: block;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4rpx;
}

.method-desc {
  font-size: 12px;
  color: #999;
}

.method-radio {
  margin-left: 20rpx;
}

.payment-actions {
  display: flex;
  gap: 20rpx;
}

.cancel-btn, .pay-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 16px;
  font-weight: 500;
  border: none;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.pay-btn {
  background: linear-gradient(135deg, #00BFFF, #0099FF);
  color: #fff;
}

.pay-btn:disabled {
  background: #ccc;
  color: #999;
}

/* 钱包余额样式 */
.wallet-balance {
  margin-bottom: 30rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
}

.balance-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.balance-label {
  font-size: 14px;
  color: #666;
}

.balance-amount {
  font-size: 18px;
  font-weight: 600;
  color: #00BFFF;
}

.balance-status {
  font-size: 12px;
  color: #52c41a;
}

.balance-status.insufficient {
  color: #ff4d4f;
}

/* 充值提示样式 */
.recharge-tip {
  margin-bottom: 30rpx;
  padding: 20rpx;
  background: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 12rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tip-content {
  display: flex;
  align-items: center;
  flex: 1;
}

.tip-text {
  margin-left: 8rpx;
  font-size: 14px;
  color: #ff4d4f;
}

.recharge-btn {
  background: #ff4d4f;
  color: #fff;
  border: none;
  border-radius: 6rpx;
  padding: 8rpx 16rpx;
  font-size: 12px;
}

/* 禁用状态样式 */
.method-item.disabled {
  opacity: 0.5;
  background: #f5f5f5;
}
</style> 